<template>
  <div class="panel">
    <el-collapse
      v-model="pageData.activeNames"
      @change="pageFn.handleCollapseChange"
    >
      <el-form
        :model="pageData.obj"
        label-width="80px"
        ref="petForm"
        :rules="pageData.rules"
      >
        <el-collapse-item
          title="订单信息"
          name="0">
          <el-row>
            <el-col :span="3">
              <el-form-item label="" label-width="35px">
                <text class="orderInfoClass">{{
                  pageData.obj.eventsOrderNo
                }}</text>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="">
                <text class="orderInfoClass">{{
                  getItemFromArray(
                    pageData.orderstatusList,
                    pageData.obj.orderStatus
                  )
                }}</text>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="报名人信息" name="1">
          <el-row>
            <el-col :span="6">
              <el-form-item label="姓名" prop="applyName">
                {{ pageData.obj.applyName }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" prop="applyPhone">
                {{ pageData.obj.applyPhone }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="微信号" prop="applyWx">
                {{ pageData.obj.applyWx }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="参与人信息" name="2">
          <el-table
            :data="pageData.obj.orderPersonList"
            stripe
            :header-cell-style="{
              backgroundColor: '#ededed',
              padding: '12px 0',
            }"
            style="width: 100%"
            border
          >
            <el-table-column prop="perName" label="姓名" />
            <el-table-column prop="perSex" label="性别">
              <template #default="{ row }">
                {{ getItemFromArray(pageData.sexList, row.perSex) }}
              </template>
            </el-table-column>
            <el-table-column prop="perPhone" label="电话" />
			<el-table-column prop="perBirthday" label="生日" />
          </el-table>
        </el-collapse-item>

        <el-collapse-item title="参与宠物信息" name="3">
          <el-table
            :data="pageData.obj.orderPetList"
            stripe
            :header-cell-style="{
              backgroundColor: '#ededed',
              padding: '12px 0',
            }"
            style="width: 100%"
            border
          >
            <el-table-column prop="petName" label="宠物名称" />
            <el-table-column prop="petBreed" label="品种" />
            <el-table-column prop="petSex" label="性别" >
            	<template #default="{ row }">
            	  {{ getItemFromArray(pageData.sexList, row.petSex) }}
            	</template>
            </el-table-column>
            <el-table-column prop="petBirthday" label="生日" />
          </el-table>
        </el-collapse-item>

        <el-collapse-item title="核销人信息" name="4">
          <el-row>
            <el-col :span="6">
              <el-form-item label="核销人">
                {{ pageData.obj.verifyName }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号">
                {{ pageData.obj.verifyPhone }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="核销备注">
                {{ pageData.obj.verifyRemark }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="活动信息" name="5">
          <el-row>
            <el-col :span="4">
                活动名称:&nbsp;{{ pageData.obj.eventsName }}
            </el-col>
            <el-col :span="4">
                报名情况:&nbsp;{{ pageData.obj.packageName }}&nbsp;
            </el-col>
            <el-col :span="4">
                报名费用:&nbsp;{{ pageData.obj.applyPrice/100 }}&nbsp;元
            </el-col>
            <el-col :span="4">
                实付费用:&nbsp;{{ pageData.obj.orderStatus === '3' ? 0 : pageData.obj.payMoney/100 }}&nbsp;元
            </el-col>
            <el-col :span="4">
                小饼干抵扣:&nbsp; {{ pageFn.biscuitDeduction(pageData.obj.biscuitDeduction) }}
            </el-col>
            <el-col :span="4">
                优惠券面值:&nbsp;{{ pageData.obj.orderStatus === '3' ? 0 : pageData.obj.couponMoney/100 }}&nbsp;元
            </el-col>
            <el-col :span="4">
                优惠券简介:&nbsp;{{ pageData.obj.orderStatus === '3' ? '' : pageData.obj.couponAbout }}
            </el-col>
            <el-col :span="4">
                邀请减免:&nbsp;{{ pageData.obj.shareDeductionMoney / 100 }}&nbsp;元
            </el-col>
            <el-col :span="4">
              报名时间: {{ pageData.obj.createdAt }}
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="其他信息" name="6">
          <el-row>
            <el-col :span="18">
              <el-form-item label="备注">
                {{ pageData.obj.orderRemark }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="退款信息" name="7">
          <el-row>
            <el-col :span="18">
              <el-form-item label="退款理由">
                {{ pageData.obj.refundRemark }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item title="评价信息" name="8">
          <el-row>
            <el-col :span="18">
              <el-form-item label="评价">
                {{ pageData.obj.reviewContent }}
              </el-form-item>
              <div  class="review_img"  v-if="!!pageData.obj.coverImage" style="margin-left:40px;margin-top:12px;"  @click="pageFn.openPanel(pageData.obj)">
                <el-image class="review_img" :src="pageData.obj.coverImage"/>
              </div>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-form>
    </el-collapse>
    <contentPopup
      v-model="pageData.showPanel"
      :data="pageData.obj"
    ></contentPopup>
  </div>
</template>

<script>
import { getEventsOrderById } from "@/api/eventsOrder.js";
import contentPopup from "../../events/eventsInfoDetail/components/contentPopup.vue";
import { ref, reactive, watchEffect, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { getItemFromArray, isLongTime } from "@/utils/tool";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "@/store";

const phoneVerifyOnRequired = (rule, value, callback) => {
  if (!value || value == "") {
    return callback("请输入手机号");
  } else {
    // 普通电话，包含座机
    // let rgx = /^((1[3456789][0-9]\d{8})|((0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?))$/
    let rgx = /^1[3456789]\d{9}$/;
    if (value.match(rgx) == null) {
      return callback("手机号格式不正确");
    } else {
      return callback();
    }
  }
};

export default {
  name: "consignOrderManage",
  components: { contentPopup },
  setup() {
    const instance = getCurrentInstance();

    const { $data: pageData, $fn: pageFn } = initData(instance);
    const { $data: petData, $fn: petFn } = petCorr();
    const { $data: commonData, $fn: commonFn } = commonFunction();

    const petDialogForm = ref(null);
    const petForm = ref(null);

    return {
      pageData,
      pageFn,
      petData,
      petFn,
      commonData,
      commonFn,
      petDialogForm,
      petForm,
      phoneVerifyOnRequired,
      getItemFromArray,
    };
  },
};

// 初始化数据
function initData(instance) {
  const store = useStore();
  const router = useRouter();
  const params = ref({});
  const query = ref({});

  watchEffect(() => {
    // 路径内参数：id
    params.value = router.currentRoute.value.params;
  });
  watchEffect(() => {
    // ？后携带参数
    query.value = router.currentRoute.value.query;
  });

  // 页面初始化对象
  const backup = {
    obj: {
      consignPhone: "",
    },
  };

  const $data = reactive({
    showPanel: false,
    type: "",
    obj: { ...backup.obj },
    activeNames: ["0", "1", "2", "3", "4", "5", "6", "7", "8"],
    showCreateOrder: true,
    // see:查看;
    operation: "",

    sexList: [
      { key: "0", name: "男" },
      { key: "1", name: "女" },
    ],
    orderstatusList: [
      {
        name: "待支付",
        key: "0",
      },
      {
        name: "已支付",
        key: "1",
      },
      {
        name: "已完成",
        key: "2",
      },
      {
        name: "已取消",
        key: "3",
      },
      {
        name: "已退款",
        key: "4",
      },
    ],
  });
  const $fn = {
    init() {
      $data.operation = query.value.operation;
      if (!!params.value && (!!params.value.id || params.value.id === 0)) {
        getEventsOrderById(params.value.id).then((res) => {
          if (res.code === 0) {
            $data.obj = res.data;
          }
        });
      }
    },
    handleCollapseChange(val) {},
    payMoneyChangeHandle(value) {
      $data.obj.payMoney = commonFunction().$fn.disposeInputValue(value);
    },
    phoneVerify(rule, value, callback) {
      if (!value || value == "") {
        return callback();
      } else {
        // 普通电话，包含座机
        // let rgx = /^((1[3456789][0-9]\d{8})|((0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?))$/
        let rgx = /^1[3456789]\d{9}$/;
        if (value.match(rgx) == null) {
          return callback("手机号格式不正确");
        } else {
          return callback();
        }
      }
    },
    parseOrderStatus(orderStatus) {
      if (!orderStatus) {
        return "";
      }
      let sta = $data.orderstatusList.find(
        (item) => item.orderStatus == orderStatus
      );
      return sta ? sta.tabName : "";
    },

    openPanel(data){
      $data.data = {...data};
      $data.showPanel = true;
    },
    biscuitDeduction(item) {
    if (!item) {
      return '未抵扣'
    } else {
      const biscuit = JSON.parse(item)
      return `${biscuit.biscuitAmount} 个小饼干抵扣 ¥${biscuit.deductionAmount / 100}`
    }
   }
  };
  $fn.init();
  return {
    $data,
    $fn,
  };
}

// 托运宠物信息相关
function petCorr() {
  const $data = reactive({
    petList: [],
    petObj: {},
    petDiglogVisible: false,
    petDialogRules: {
      petName: [{ required: true, message: "请填写宠物名称", trigger: "blur" }],
      petType: [{ required: true, message: "请填写宠物品种", trigger: "blur" }],
      petWeight: [
        { required: true, message: "请填写宠物重量", trigger: "blur" },
      ],
    },
  });

  const $fn = {
    petAdd() {
      $data.petObj = {};
      $data.petDiglogVisible = true;
    },
    petUpdate(row) {
      $data.petObj = {};
      $data.petObj = JSON.parse(JSON.stringify(row));
      $data.petDiglogVisible = true;
    },
    petDelete(row) {
      ElMessageBox.confirm("是否确认删除当前宠物信息？", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let index = $data.petList.findIndex(
            (res) =>
              (!!res.id && res.id === row.id) ||
              (!!res.uuid && res.uuid === row.uuid)
          );
          if (index >= 0) {
            $data.petList.splice(index, 1);
          }
        })
        .catch(() => {});
    },
    petPrimary(formEl) {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          // 存在id，或uuid属性，则为编辑
          if (!!$data.petObj.id || !!$data.petObj.uuid) {
            $data.petList.forEach((item) => {
              if (
                (!!item.id && item.id === $data.petObj.id) ||
                (!!item.uuid && item.uuid === $data.petObj.uuid)
              ) {
                item.petName = $data.petObj.petName;
                item.petType = $data.petObj.petType;
                item.petWeight = $data.petObj.petWeight;
              }
            });
          } else {
            $data.petObj.uuid = commonFunction().$fn.getUUID(8, 16);
            $data.petList.push($data.petObj);
          }
          $data.petObj = {};
          $data.petDiglogVisible = false;
        } else {
          return false;
        }
      });
    },
    petCancel() {
      $data.petObj = {};
      $data.petDiglogVisible = false;
    },
    petWeightChangeHandle(value) {
      $data.petObj.petWeight = commonFunction().$fn.disposeInputValue(value);
    },
  };

  return {
    $data,
    $fn,
  };
}

function commonFunction() {
  const $data = reactive({});

  const $fn = {
    disposeInputValue(num) {
      if (!num && num != "0") {
        return "";
      }
      let str = num;
      let len1 = str.substr(0, 1);
      let len2 = str.substr(1, 1);
      //如果第一位是0，第二位不是点，就用数字把点替换掉【去掉数字前面无用的0】
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      //第一位不能是.
      if (len1 == ".") {
        str = "";
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换
      str = str.replace(/[^\d^.]+/g, ""); // 保留数字和小数点
      if (str.indexOf(".") == -1 || str.indexOf(".") == str.length - 1) {
        return str;
      }
      let tempNum = str * 100;
      tempNum = parseInt(tempNum);
      str = tempNum / 100;
      return str;
    },
    /***
     * 获取请求的UUID，指定长度和进制,如
     * getUUID(8, 2)   //"01001010" 8 character (base=2)
     * getUUID(8, 10) // "47473046" 8 character ID (base=10)
     * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
     */
    getUUID(len, radix) {
      let chars =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
          ""
        );
      let uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (let i = 0; i < len; i++)
          uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (let i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
  };

  return {
    $data,
    $fn,
  };
}
</script>

<style scoped lang="scss">
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.video-info {
  display: inline-block;
  padding-left: 12px;
  line-height: 24px;
  vertical-align: bottom;
}
.isEmpty {
  color: rgb(172, 172, 172);
}
.content-main {
  .blockBg {
    display: inline-block;
    vertical-align: top;
  }
  .imgBg {
    display: inline-block;
  }
}
:deep(.el-collapse-item__header) {
  font-size: 16px;
  font-weight: bold;
}
.pet-table-head {
  padding: 8px 0;
  line-height: 32px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
:deep(.el-input__inner) {
  width: 100%;
}
.pageButton {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  margin-right: 50px;
  margin-bottom: 10px;
}
.orderInfoClass {
  font-size: 16px;
  font-weight: bold;
}

.review_img {
  width: 100px;
  height: 100px;
}
</style>
